package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CreateProjectException;
import com.heima.model.common.constants.UserConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.EmptyUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 自媒体登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1. 检查参数
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验用户是否存在 查询用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName())
                .eq(WmUser::getStatus, UserConstants.AP_USER_REALNAME_CHECK_TRUE));
        if(EmptyUtil.isNullOrEmpty(wmUser)){
            CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.比对密码是否正确
        String dtoPassword = dto.getPassword() + wmUser.getSalt();
        if ( !DigestUtils.md5DigestAsHex(dtoPassword.getBytes()).equals(wmUser.getPassword())){
            CreateProjectException.exec(AppHttpCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        //4.修改用户登陆时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        //5.返回jwt加密token
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",wmUser);
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}












